﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml;

namespace iTunesLibrary.Dal.Xml
{
    public static class ParserExt
    {
        public static XDocument ExtractNode(this XContainer root, string attributeName)
        {
            var keyNode = root.Nodes().FirstOrDefault(node =>
                {
                    return
                node.NodeType == XmlNodeType.Element
                && ((XElement)node).Value == attributeName;
                });
            if (keyNode == null)
            {
                return null;
            }

            var valueNode = (XDocument)keyNode.NextNode.Document;
            return valueNode;
        }

        public static string ExtractString(this XContainer root, string attributeName)
        {
            var keyNode = root.Nodes().FirstOrDefault(node => node.NodeType == XmlNodeType.Element && ((XElement)node).Value == attributeName);
            if (keyNode == null)
            {
                return null;
            }

            var valueNode = (XElement)keyNode.NextNode;
            if (valueNode == null || String.IsNullOrEmpty(valueNode.Value))
            {
                return null;
            }

            return valueNode.Value;
        }
        public static int ExtractInt(this XContainer root, string attributeName)
        {
            string value = root.ExtractString( attributeName);
            return String.IsNullOrEmpty(value) ? 0 : Int32.Parse(value);
        }

    }
}
